package com.google.project.server;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.project.client.Service.ProjectReportService;
import com.google.project.server.entity.Project;
import com.google.project.server.entity.ProjectReport;
import com.google.project.server.entity.ProjectReportDetail;
import com.google.project.shared.ProjectReportDTO;
import com.google.project.shared.ProjectReportDetailDTO;

@SuppressWarnings("serial")
public class ProjectReportServiceImpl extends RemoteServiceServlet implements
		ProjectReportService {

	@Override
	public ProjectReportDTO addProjectReport(ProjectReportDTO projectReportDTO,
			String projectId, List<ProjectReportDetailDTO> listReportDetail) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		ProjectReport projectReport=null;
		try {
			 Project project =   pm.getObjectById(Project.class, projectId);
			 projectReport = new ProjectReport(projectReportDTO);
			 project.getListOfProjectReport().add(projectReport);
			 pm.makePersistent(project);
		     addListReportDetail(projectReport.getId(),listReportDetail);
			 
		} finally {
			pm.close();
		}
		return projectReport.toDTO();
	}

	private void addListReportDetail(String projectReportId,
			List<ProjectReportDetailDTO> listReportDetail) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		ProjectReportDetail reportDetail=null;
		try {
			ProjectReport projectReport=pm.getObjectById(ProjectReport.class,projectReportId);
			for (ProjectReportDetailDTO projectReportDetailDTO : listReportDetail) {
				reportDetail=new ProjectReportDetail(projectReportDetailDTO);
				reportDetail.setReportId(projectReportId);
				projectReport.getListOfReportDetail().add(reportDetail);
				pm.makePersistent(projectReport);
			}
			 
		} finally {
			pm.close();
		}
		
		
		
	}

	@Override
	public List<ProjectReportDTO> getAllProjectReport() {
		List<ProjectReportDTO> listReportDTO=new ArrayList<ProjectReportDTO>();
		PersistenceManager pm=PMF.get().getPersistenceManager();
		Query q = pm.newQuery(ProjectReport.class);
		try {
			List<ProjectReport> list = (List<ProjectReport>) q.execute();
			for (ProjectReport report : list) {
				listReportDTO.add(report.toDTO());
			}
		} catch (Exception e) {
			// logger.warning(e.getMessage());
		} finally {
			pm.close();
		}
		return listReportDTO;
	}
	
	//update projectReport status
	@Override
	public void updateStatusProjectReport(String id,int status) {

		PersistenceManager pm = PMF.get().getPersistenceManager();
		ProjectReport projectReport = null;
		try {
			projectReport = pm
					.getObjectById(ProjectReport.class, id);
			ProjectReportDTO data=new ProjectReportDTO();
			data=projectReport.toDTO();
			data.setStatus(status);
			projectReport.updateFromDTO(data);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			pm.close();
		}
	}
}
